﻿/*
* Activity Tracking Log v0.1.1 - http://activitytrackinglog.codeplex.com
* Activity Tracking Log for ASP.Net & ASP.Net MVC
* Copyright (c) 2011 Vadim Burac
* Licensed under the Microsoft Public License (Ms-PL)
* http://activitytrackinglog.codeplex.com/license
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using ActivityTrackingLog.Utils;

namespace ActivityTrackingLog.Web.Helpers.MvcActionFilters
{
    public enum ExecutingStep
    {
        Both,
        BeforeAction,
        AfterAction
    }

    [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class LogActivityAttribute : ActionFilterAttribute
    {
        public ExecutingStep ExecutingStep { get; set; }
        public bool LogControllerNameActionName { get; set; }
        public Enum Category { get; set; }
        public Enum Activity { get; set; }

        public LogActivityAttribute()
        {
            ExecutingStep = MvcActionFilters.ExecutingStep.BeforeAction;
            LogControllerNameActionName = true;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (this.ExecutingStep == MvcActionFilters.ExecutingStep.Both || 
                this.ExecutingStep == MvcActionFilters.ExecutingStep.BeforeAction)
                LogActivity(filterContext, false);
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (this.ExecutingStep == MvcActionFilters.ExecutingStep.Both || 
                this.ExecutingStep == MvcActionFilters.ExecutingStep.AfterAction)
                LogActivity(filterContext, true);
        }

        #region helpers

        private void LogActivity(ControllerContext context, bool isPostAction)
        {
            if (!LogControllerNameActionName)
                Log.LogActivity(Category, Activity, isPostAction);
            else
            {
                string controllerName = context.RouteData.Values["controller"] as string;
                string actionName = context.RouteData.Values["action"] as string;

                Log.LogActivity(controllerName, actionName, isPostAction);
            }

        }

        #endregion
    }
}
